package top.frsf.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import top.frsf.reggie.dto.DishDto;
import top.frsf.reggie.entity.DishFlavor;
import top.frsf.reggie.mapper.DishMapper;
import top.frsf.reggie.entity.Dish;
import top.frsf.reggie.service.DishFlavorService;
import top.frsf.reggie.service.DishService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 菜品管理(Dish)表服务实现类
 *
 * @author makejava
 * @since 2023-01-15 00:37:12
 */
@Service("dishService")
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;


    /**
     * @Author: FRSF
     * @Date: 2023/1/16 16:15
     * @Description 新增菜品，同时添加菜品口味
     * @param dishDto:
     * @return: void
     */
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        // 保存菜品的基本信息到菜品表dish
        this.save(dishDto);

        // MP插入数据后，自动回显ID，flavors封装dishID
        Long genDishId = dishDto.getId();
        // 菜品口味列表
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(genDishId);
        }

        // 保存菜品口味到口味表dish_flavor
        dishFlavorService.saveBatch(flavors);
    }


    /**
     * @Author: FRSF
     * @Date: 2023/1/26 17:46
     * @Description 根据ID查询菜品信息和对应口味信息
     * @param id:
     * @return: top.frsf.reggie.dto.DishDto
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        // 查询菜品基本信息
        Dish dish = this.getById(id);

        // 查询当前菜品对应口味信息
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(wrapper);

        // 拷贝进入dishDto
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        dishDto.setFlavors(flavors);

        return dishDto;
    }


    /**
     * @Author: FRSF
     * @Date: 2023/1/26 18:02
     * @Description 更新菜品信息，并且更新对应的口味信息
     * @param dishDto:
     * @return: void
     */
    @Override
    public void updateWithFlavor(DishDto dishDto) {
        // 更新Dish表基本信息
        this.updateById(dishDto);

        // 清理当前菜品对应的所有口味数据
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(wrapper);

        // 添加当前提交的新口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(flavors);
    }
}

